﻿using System;
using RuTracker.Interface;
using RuTracker.Interface.Dropbox;
using RuTrackerLib.ServiceAttibutes;

namespace RuTrackerLib.Tracker
{
    [PerCallService]
    public class TorrentsLoader
    {
        private readonly IUserRepository _userRepository;
        private readonly IDropBoxAccessor _dropboxAccessor;
        private readonly ITrackerAccessor _trackerAccessor;

        public TorrentsLoader(IUserRepository userRepository
            , IDropBoxAccessor dropboxAccessor
            , ITrackerAccessor trackerAccessor)
        {
            _userRepository = userRepository;
            _dropboxAccessor = dropboxAccessor;
            _trackerAccessor = trackerAccessor;
        }

        public void DownloadTorrent(UserStorageInfo storageInfo, string torrentUrl)
        {
            byte[] torrent = _trackerAccessor.GetTorrentFromTopic(new Uri(torrentUrl));
            UploadFileToStorage(storageInfo.StorageFolder, torrent, storageInfo.Token.ToArray());
            _userRepository.DownloadTorrent(storageInfo.User.Name, torrentUrl);
        }

        private void UploadFileToStorage(string folder, byte[] torrentFile, byte[] token)
        {
            Log.Debug("Connecting to DropBox account");
            _dropboxAccessor.Connect(token);

            string fileName = GenerateFileName();

            Log.Debug("Loading DropBox hierarchy");
            StorageFolder rootFolder = _dropboxAccessor.LoadHierarchy();
            Log.Debug("DropBox hierarchy loaded");

            StorageFolder folderToUpload = rootFolder.GetChild(folder) as StorageFolder;
            Log.Debug("Uploading file '{0}' to folder: '{1}'", fileName, folder);
            _dropboxAccessor.UploadFile(fileName, folderToUpload, torrentFile);

            _dropboxAccessor.Disconnect();
        }

        private string GenerateFileName()
        {
            string fileName = DateTime.Now.ToString("dd-MM-yyyy-hh-mm-ss") + ".torrent";
            return fileName;
        }
    }
}
